package gmusic.servlet;

import gmusic.command.Accueil;
import gmusic.command.Command;
import gmusic.command.CommandExport;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

public class ActionMappingServlet extends HttpServlet {

	private final static Logger log = Logger
			.getLogger(ActionMappingServlet.class);

	public void init() throws ServletException {

	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		//log.debug("Path : " + request.getRequestURI());

		try {
			RequestDispatcher rd = null;
			String next = null;
			String cmd = request.getRequestURI();
			cmd = cmd.substring(cmd.lastIndexOf("/") + 1, cmd.length() - 3);
			// log.debug("ActionMappingServlet --> " + cmd);
			if (cmd.startsWith("Export")) {
				try {
					Class<CommandExport> classe = (Class<CommandExport>) Class
							.forName("gmusic.command." + cmd);
					Constructor<CommandExport> constructeur = classe
							.getConstructor();
					Object instance = constructeur.newInstance();
					Class<CommandExport>[] paramTypes = new Class[2];
					paramTypes[0] = (Class<CommandExport>) Class
							.forName("javax.servlet.http.HttpServletRequest");
					paramTypes[1] = (Class<CommandExport>) Class
							.forName("javax.servlet.http.HttpServletResponse");
					Method m = classe.getMethod("execute", paramTypes);
					next = (String) m.invoke(instance, request, response);
				} catch (Exception e) {
					log.error("Commande export \"" + cmd + "\" inconnu");
					next = new Accueil().execute(request);
					log.error("Exception reflexion : ", e);
				}
			} else {
				try {
					Class<Command> classe = (Class<Command>) Class
							.forName("gmusic.command." + cmd);
					Constructor<Command> constructeur = classe.getConstructor();
					Object instance = constructeur.newInstance();
					Class<Command>[] paramTypes = new Class[1];
					paramTypes[0] = (Class<Command>) Class
							.forName("javax.servlet.http.HttpServletRequest");
					Method m = classe.getMethod("execute", paramTypes);
					next = (String) m.invoke(instance, request);
				} catch (Exception e) {
					log.error("Commande \"" + cmd + "\" inconnu");
					next = new Accueil().execute(request);
					log.error("Exception reflexion : ", e);
				}
				rd = getServletContext().getRequestDispatcher(next);
				rd.forward(request, response);
			}

		} catch (Exception e) {
			log.error("ERREUR");
		}
	}
}
